Shader "Prota/DrawDepth"
{
    Properties
    {
        _CameraDepthTexture ("CameraDepthTexture", 2D) = "white" { }
        
        [Toggle] _Ranged ("Ranged", Float) = 0
        _RangeFrom ("Range From", float) = 0.0
        _RangeTo ("Range To", float) = 1.0
        
        [Toggle] _InputIsLinearDepth ("Input is Linear Depth", Float) = 0
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always
        
        Blend SrcAlpha OneMinusSrcAlpha
        
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            #include "..\..\ShaderUtils\ProtaUtils.cginc"
            
            sampler2D _CameraDepthTexture;
            
            float _Ranged;
            float _RangeFrom;
            float _RangeTo;
            
            // 对于 Orthographic 摄像机, 输入的深度图已经是线性的, 并且近裁面1, 远裁面0.
            // https://forum.unity.com/threads/using-_cameradepthtexture-with-orthographic-camera.639922/
            float _InputIsLinearDepth;
            
            float4 frag (v2f v) : SV_Target
            {
                float depth = tex2D(_CameraDepthTexture, v.uv);
                
                if(_InputIsLinearDepth)
                {
                    depth = Linear01Depth(depth);
                }
                else
                {
                    depth = 1 - depth;
                }
                
                if(_Ranged)
                {
                    float near = _ProjectionParams.y;
                    float far = _ProjectionParams.z;
                    float d = far - near;
                    depth = xmap(depth * d + near, _RangeFrom, _RangeTo, 0, 1);
                }
                return float4(clamp(depth, 0, 1), 0, 0, 1);
            }
            ENDCG
        }
    }
}
